<script setup lang="ts">
import { completeTask, getFlowJsonByProcessInstanceId, getHistoryNode, getTaskPermission, terminationProcess } from '/@/api/flow/flow';
import { queryList as queryUserList } from '/@/api/admin/user';
import { deptRoleList as queryRoleList } from '/@/api/admin/role';
import { formatTimestamp } from '/@/utils/timeUtil';
import { useMessage } from '/@/hooks/message';
import { Back, Check, Close } from '@element-plus/icons-vue';
import { formCreate } from '../../../lib/formCreate/index.es';

const emit = defineEmits(['refresh']);
const rule = ref([]);

const drawer = ref(false);
const loading = ref(false);

const statLoading = ref(false);
const flowLoading = ref(true);
const historyNodeLoading = ref(true);
const taskIdRef = ref('');
const approvalForm = ref({
	approvalOpinion: null,
});
const rules = ref({
	approvalOpinion: [{ required: true, message: '审批意见不能为空', trigger: 'blur' }],
});
const approvalFormRef = ref();
const historyNode = ref({
	activityInstanceList: [],
});
const form = ref({
	id: '',
});
const currentNodeList = ref([]);

const process = ref({
	id: 'root',
	pid: undefined,
	type: 'start',
	name: '发起人',
	executionListeners: [],
	formProperties: [],
	child: {
		id: 'end',
		pid: 'root',
		type: 'end',
		name: '流程结束',
		executionListeners: [],
		child: undefined,
	} as EndNode,
} as StartNode);

let userList = [];

let roleList = [];

const getUserList = (ids?: string[]) => {
	return ids === undefined
		? userList
		: userList.filter((s) => {
			return ids.indexOf(s.id) != -1;
		});
};
const getUserInfo = (id?: string) => {
	return userList.find((user) => user.id === id);
};

const getRoleById = (roleId?: string) => {
	return roleList.find((role) => role.id === roleId);
};

const getRoleList = (roleIds?: string[]) => {
	return roleIds === undefined
		? roleList
		: roleList.filter((s) => {
			return roleIds.indexOf(s.id) != -1;
		});
};

const approval = (status: string) => {
	approvalFormRef.value.validate((valid, fields) => {
		if (valid) {
			loading.value = true;
			completeTask({
				taskId: taskIdRef.value,
				comment: approvalForm.value.approvalOpinion,
				params: form.value,
				status: status,
			}).then((res) => {
				loading.value = false;
				drawer.value = false;
				useMessage().success('操作成功');
				emit('refresh');
			});
		}
	});
};
const terminationFlow = () => {
	approvalFormRef.value.validate((valid, fields) => {
		if (valid) {
			loading.value = true;
			terminationProcess({
				taskId: taskIdRef.value,
				comment: approvalForm.value.approvalOpinion,
				params: form.value,
				status: '2',
			}).then((res) => {
				loading.value = false;
				drawer.value = false;
				useMessage().success('操作成功');
				emit('refresh');
			});
		}
	});
};

const openDialog = (processInstanceId: string, oRule: object, variables: object, taskId: string) => {
	approvalForm.value.approvalOpinion = '';
	taskIdRef.value = taskId;
	rule.value = oRule.formJson;
	form.value = variables;
	drawer.value = true;
	flowLoading.value = true;
	historyNodeLoading.value = true;
	queryUserList([]).then((res) => {
		userList = res.data.map((item) => {
			return {
				id: item.userId,
				name: item.name,
				username: item.username,
				avatar: item.avatar,
			};
		});
	});

	queryRoleList().then((res) => {
		roleList = res.data.map((item) => {
			return {
				id: item.roleId,
				name: item.roleName,
			};
		});
	});

	getFlowJsonByProcessInstanceId(processInstanceId).then((res) => {
		process.value = JSON.parse(res.data.flowJson);
		flowLoading.value = false;
	});
	getHistoryNode(processInstanceId).then((res) => {
		historyNode.value = res.data;
		currentNodeList.value = res.data.activityInstanceList.filter((item) => !item.completeEd).map((item) => item.activityId);
		historyNodeLoading.value = false;
	});

	nextTick(() => {
		if (taskId) {
			getTaskPermission(taskId).then((res) => {
				const fieldList = res.data.fieldList;
				const disabledFieldList = [];
				fieldList
					.filter((item) => {
						return item.readonly;
					})
					.forEach((item) => {
						disabledFieldList.push(item.id);
					});
			});
		}
	});
};
defineExpose({
	openDialog,
});
const getTime = (durationInMillis) => {
	const time = formatTimestamp(durationInMillis);
	let timeString = '';
	if (time.day > 0) {
		timeString = time.day + '天' + time.hour + '小时' + time.minutes + '分钟' + time.seconds + '秒';
	} else if (time.hour > 0) {
		timeString = time.hour + '小时' + time.minutes + '分钟' + time.seconds + '秒';
	} else if (time.minutes > 0) {
		timeString = time.minutes + '分钟' + time.seconds + '秒';
	} else {
		timeString = time.seconds + '秒';
	}
	return timeString;
};
const options = ref({
	submitBtn: {
		show: false,
	},
});

const getBorderBlink = (task) => {
	if (taskIdRef.value) {
		if (task.currentEd) {
			return 'borderBlink';
		}
	} else {
		if (task.assigneeEd) {
			return 'borderBlink';
		}
	}
};

function getTaskEndTimeColor(item) {
	if (item.taskList || item.taskList.length == 0) {
		return '#0bbd87';
	}
	return item.taskList[item.taskList.length - 1].endTime ? '#0bbd87' : '#f60000';
}

function getTaskEndTimeIcon(item) {
	if (item.taskList || item.taskList.length == 0) {
		return '';
	}
	return item.taskList[item.taskList.length - 1].endTime ? '' : 'MoreFilled';
}

const getCommentTitle = (task: object) => {
	let commentTitle = '审批意见';
	if (!task || !task.variables) {
		return commentTitle;
	}
	const status = task.variables['mobai_flow_status'];

	switch (status) {
		case '1':
			commentTitle = '驳回原因';
			break;
		case '2':
			commentTitle = '终止原因';
			break;
	}
	return commentTitle;
};
</script>

<template>
	<el-drawer v-model="drawer" size="100%" title="流程详情">
		<template #header>
			<div>
				<el-text size="large" type="primary">流程详情</el-text>
				<el-divider />
			</div>
		</template>
		<div
			style="display: flex; justify-content: space-between; flex-direction: row; height: 100%; width: 100%"
			v-loading="(flowLoading && historyNodeLoading) || loading"
		>
			<div style="height: 100%; width: 50%; position: relative; overflow: auto" class="infinite-list">
				<el-affix style="position: absolute; top: 0" :offset="150">
					<el-tag size="large">流程图</el-tag>
				</el-affix>

				<flow-design
					:process="process"
					:fields="[]"
					:readOnly="true"
					:getUserList="getUserList"
					:getUserInfo="getUserInfo"
					:getRoleList="getRoleList"
					:getRoleById="getRoleById"
					:currentNode="currentNodeList"
				>
				</flow-design>
			</div>

			<div
				style="
					height: 100%;
					width: 50%;
					overflow: auto;
					display: flex;
					justify-content: center;
					align-items: center;
					flex-direction: column;
					position: relative;
				"
				class="infinite-list"
			>
				<el-affix :offset="150" style="position: absolute; top: 0; left: 0">
					<el-tag size="large">审批记录</el-tag>
				</el-affix>
				<el-timeline style="max-width: 600px; position: absolute; top: 0">
					<el-timeline-item
						color="#0bbd87"
						v-if="historyNode.startUser"
						center
						placement="top"
						:timestamp="'发起人 发起时间：' + historyNode.startTime"
					>
						<el-card style="position: relative" body-style="display: flex;flex-direction: column">
							<div style="display: flex; align-items: center">
								<el-avatar
									fit="fill"
									:src="
										historyNode.startUser.avatar
											? 'api' + historyNode.startUser.avatar
											: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
									"
									@error="true"
								>
									<img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
								</el-avatar>
								<div class="assigneeContent" style="margin-left: 2em">
									<div>
										<span>用户名：</span>
										<el-tag type="warning">{{ historyNode.startUser.username }}</el-tag>
									</div>
									<div>
										<span>姓名：</span>
										<el-tag type="warning">{{ historyNode.startUser.name }}</el-tag>
									</div>
									<div>
										<span>所属部门：</span>
										<el-tag type="warning">{{ historyNode.startUser.deptName }}</el-tag>
									</div>
								</div>
							</div>
						</el-card>
					</el-timeline-item>
					<el-timeline-item
						v-for="item in historyNode.activityInstanceList"
						center
						:timestamp="item.name + ' 开始时间：' + item.startTime"
						placement="top"
						:color="getTaskEndTimeColor(item)"
						:icon="getTaskEndTimeIcon(item)"
					>
						<el-card>
							<el-timeline style="max-width: 600px">
								<el-timeline-item
									v-for="task in item.taskList ? item.taskList : []"
									:timestamp="task.assignee.username + '审批   开始时间：' + task.startTime"
									center
									placement="top"
									:color="task.endTime ? '#0bbd87' : '#f60000'"
									:icon="task.endTime ? '' : 'MoreFilled'"
								>
									<el-card body-style="display: flex;flex-direction: column" :class="getBorderBlink(task)">
										<div style="display: flex; align-items: center">
											<el-avatar
												fit="fill"
												:src="
													task.assignee.avatar ? 'api' + task.assignee.avatar : 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
												"
												@error="true"
											>
												<img src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
											</el-avatar>
											<div class="assigneeContent" style="margin-left: 20px" v-if="task.endTime">
												<div>
													<span>{{ getCommentTitle(task) }}</span>
													<div>
														<el-tag type="success">
															<el-tooltip placement="top" :content="task.comment">
																<el-text :truncated="true" style="max-width: 6em">{{ task.comment }}</el-text>
															</el-tooltip>
														</el-tag>
													</div>
												</div>
												<div>
													<span>结束时间：</span>
													<el-tag type="warning">{{ task.endTime }}</el-tag>
												</div>
												<div v-if="task.endTime">
													<span>总时长：</span>
													<el-tag type="warning">{{ getTime(task.durationInMillis) }}</el-tag>
												</div>
											</div>

											<div style="margin-left: 20px" v-if="!task.endTime">正在审批</div>
										</div>
									</el-card>
								</el-timeline-item>
								<el-timeline-item center :color="getTaskEndTimeColor(item)" />
							</el-timeline>
						</el-card>
					</el-timeline-item>
					<el-timeline-item center :color="historyNode.endTime ? '#0bbd87' : '#f60000'" />
				</el-timeline>
			</div>
		</div>
	</el-drawer>
</template>

<style scoped lang="scss">
.assigneeContent > div {
	margin-top: 0.5em;
	min-width: 250px;
	display: flex;
	justify-content: flex-start;
}

.assigneeContent > div > span {
	min-width: 6rem;
}

:deep(label) {
	width: auto !important;
}

.borderBlink {
	box-shadow: 5px 5px 20px 2px rgba(50, 177, 0, 0.4);
}
</style>
